// pages/balance_recharge/balance_recharge.js
var yz_pay = require("../../../../mycomponent/yz_pay/yz_pay");
const skinBehavior = require('../../../../utils/themeSkin/skinBehavior');
var location = require("../../../../mybehaviors/location/location");
var app = getApp();
function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}
Page({
  behaviors: [yz_pay,skinBehavior,location],
  /**
	 * 页面的初始数据
	 */
  data: {
    language: '',
    credit2: 0,
    buttons: [],
    typename: '',
    recharge: '',
    ordersn: '',
    money: '',
    diymoney: '',//自定义输入的金额
    diy_money_index: null,

    activatDes: {},
    // 选择的充值方式
    pay_type: '',
    balanceLang: '余额',
    priceDifferencePool:false,
    // 充值标签
    tagBalance:false,
    tagName:'',
    plugName:'',
    // 新充值接口页面内容,后续插件跟商城余额充值页面优化也用这套
    activity_new: [],
    buttons_new: [],
    display_switch_new: [],
    plugins_new: [],
    couponShowPopup:false,
    use_coupon_size_new:0,
    show:false,
    storeNameKey:'',
    page:1,
    total_page:1,

    need_sign: false,
    sign_info: {},
    min_recharge: null,//最低起充金额
    diy_amount: [],//自定义充值金额
    plugin_code: {},//插件名，用于处理不同的插件充值逻辑，如果后续有多个插件同时使用，可以用逗号隔开
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    if(options.name == 'pdp'){
      //#feat#14800 price-difference-pool 插件的充值页 复用样式
      this.setData({
        priceDifferencePool:true
      })
    }
    if(options.name == 'balance_rechargeTag'){
      this.setData({
        tagBalance:true,
      })
    }
    if(options.name == 'YccRecharge'){
      this.setData({
        plugName : "YccRecharge"
      })
    }
    console.log(options.balance);
    if(options.balance){
      this.setData({
        money:options.balance
      });
    }
    if(options.plugin){
      this.setData({
        plugin:options.plugin
      })
    }
    try {
      // let value = wx.getStorageSync('balance');
      let value = wx.getStorageSync('balance');
      value = value || "余额";
      if (value) {
        this.setData({
          balanceLang: value
        });
        if(this.priceDifferencePool){
          this.setData({diyname:basic_info.price_difference_pool_name?basic_info.price_difference_pool_name:'资金池'})
        }
      }
    } catch (e) {
      console.log(e);
    }
  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },
  onShow:function(){
    this.getData(); // 初始化参数
  },
  invoiceShowAddressFun(){
    this.setData({
      showAddressList: true,
      addressList_caller:"invoice"
    });
  },
  
  confirmSelectAddress(e) {
    let info;
    if (e.detail.loc) {
      info = e.detail.form;
    } else {
      info = e.detail;
    }
    if(this.data.addressList_caller == "invoice") {
      this.selectComponent('.invoicePop').setAddress(info);
      this.setData({
        showAddressList: false,
      });
    }
  },
  subInvoice(data) {
    // 弹窗获取发票数据
    this.setData({
      invoice_list: data.detail, //72638
    });
    this.moneyChange();
  },
  tapStoreID(e) {
    let {
      item
    } = e.currentTarget.dataset;
    console.log(item,'dddddddd')
    this.setData({
      store_id: item.id,
      full_address: item.full_address,
    })
    if (item.diy_amount.length > 0){
      this.setData({
        diy_amount: item.diy_amount
      })
    }
    if (item.activity.length != 0) {
      const index = this.data.activity_new.findIndex(ele => ele.code === "store-oil-station");
      if (index !== -1) {
        this.data.activity_new[index] = item.activity;
      } else {
        this.data.activity_new.push(item.activity);
      }
    } else {
      this.data.activity_new = this.data.activity_new.filter(ele => ele.code !== "store-oil-station");
    }
    this.setData({
      activity_new:this.data.activity_new
    })
    this.showClose();
  },
  showClose(){
    this.moneyChange();
    this.setData({
      show:false,
      storeNameKey:"",
      stroeList:[],
      page:1,
      total_page:0
    })
  },
  async getStoreList(e,key = false) {
    console.log(e)
    let json = {
      lng: this.data.point?.lng,
      lat: this.data.point?.lat,
      city: this.data?.city,
      name : this.data.storeNameKey
    }
    console.log(key,'wwwwwwwwwww')
    if(key){
      this.setData({
        page : this.data.page + 1
      })
      json.page = this.data.page ;
    }
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.store-oil-station.frontend.oil-store.index"),
      data: json
    })
    if (data.result) {
      if(key){
        this.setData({
          stroeList:this.data.stroeList.concat(data.data.data)
        })
        return
      }
      this.setData({
        page: 1,
        total_page: data.data.last_page,
        stroeList: data.data.data,
        show: true,
      })
    } else {
      if(key){
        this.setData({
          page : this.data.page - 1,
          total_page:0
        })
        return
      }
      app.tips(data.msg);
    }
  },
  async getMoreData(e){
    this.getStoreList(e,true)
  },  
  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {},
  couponClose(){
    this.setData({
      couponShowPopup:false
    })
  },
  //新优惠券组装json信息
  assembleCoupons_new(arr) {
    // 使用 map() 直接获取id数组，然后 join() 方法将其连接成字符串
    return arr.map(item => item.id).join(",");
  },
  childSelectCoupon(e){
    console.log(e)
    let ids = this.assembleCoupons_new(e.detail.checkCouponList_new);
    this.setData({
      member_coupon_ids:ids?ids:'',
      use_coupon_size_new:e.detail.use_coupon_size_new
    })
    console.log(this.data.use_coupon_size_new,'suse_coupon_size_new')
    this.moneyChange();
  },
  couponShow(){
    this.setData({
      couponShowPopup:true
    })
  },
  async new_getData(json,urls){
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss(urls),
      data:json
    })
    if(data.result){
      this.setData({
        credit2:data.data.credit2,
        activity_new:data.data.activity,
        buttons_new:data.data.buttons,
        buttons:data.data.buttons,
        display_switch_new:data.data.display_switch,
        plugins_new:data.data.plugins,
        recharge:1,
        full_address:data.data.plugins?.store?.full_address
      })
      if(data.data.plugins.store){
        this.setData({
          store_id:this.data.plugins_new.store.id
        })
      }
      if(this.data.plugins_new.balance_invoice){
        this.selectComponent('.invoicePop').initData({sinvoice: this.data.plugins_new.balance_invoice});
      }
      for (let i = 0; i < this.data.buttons.length; i++) {
        if (this.data.buttons[i]) {
          this.setData({
            ['buttons[' + i + '].btclass']: this.btnclass(this.data.buttons[i].value)
          });
        }
      }
      if (this.data.plugins_new?.store_oil_station?.diy_amount.length > 0){
        this.setData({
          diy_amount: this.data.plugins_new?.store_oil_station?.diy_amount
        })
      }
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: this.data.themeBaseColor,
        animation: {
          duration: 400,
          timingFunc: 'easeIn'
        }
      });
      
    }else{
      app.tips(data.msg);
    }
  },
  // 初始化参数
  async getData() {
    let that = this;
    let urls = "finance.balance.balance";
    let json = {};
    if(this.data.priceDifferencePool){
      urls = 'plugin.price-difference-pool.frontend.modules.pool.controllers.recharge.page';
    }else if (this.data.tagBalance){
      urls = "plugin.tag-balance.frontend.recharge.page";
    }else if (this.data.plugName == 'YccRecharge'){
      urls = "plugin.ycc-money.frontend.recharge.index";
    } else if (this.options.plugin == 'store_oil_station'){
      console.log('store_oil_station')
      urls = "finance.balance-recharge.page";
      await this._getLocation((res) => {
        json.city = res.address_component.city;
        json.lng = res.location.lng;
        json.lat = res.location.lat;
        json.plugin = this.options.plugin;
        this.data.point = {
          lng: res.location.lng,
          lat: res.location.lat,
          city: res.address_component.city
        }
        this.new_getData(json,urls);
      },(e)=>{
        wx.showModal({
          title: '定位失败',
          content: '请确认授权定位是否开启',
          confirmText:'手动定位',
          complete: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/packageC/o2o/o2oLocation_loc/o2oLocation_loc?tag=oil',
              })
            }
          }
        })
      })
      return
    }
    let urlStr = app.getNetAddresss(urls);
    app._postNetWork({
      url: urlStr,
      data:json,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          if(this.data.priceDifferencePool){
            this.setData({
              credit2:res.data.pool,
              buttons:res.data.buttons,
              recharge:1
            })
            return
          }
          if(this.data.tagBalance){
            this.setData({
              credit2:res.data.balance,
              buttons:res.data.button,
              typename:'充值',
              recharge:1,
              diyname:res.data.tag?.tag_name
            })
            return
          }
          if(this.data.plugName == 'YccRecharge'){
            this.setData({
              balanceLang:'余额',
              credit2:res.data.plugin_member.amount,
              recharge:1,
              buttons:res.data.payment_list,
              recharge_double:res.data.recharge_double,
              plugin_name:res.data.plugin_name
            })
            return
          }
          that.setData({
            credit2: res.data.credit2,
            buttons: res.data.buttons,
            typename: res.data.typename,
            recharge: res.data.recharge,
            activatDes: res.data.remark,
            need_sign: res.data.need_sign,//是否需要签署合同
            sign_info: res.data.sign_info || {},//合同信息
            min_recharge: res.data.min_recharge,
            diy_amount: res.data?.diy_amount || [],
            plugins_new: res.data?.plugins||{},
            bottom_content: res.data?.bottom_content,
            top_img: res.data?.top_img
          });
          for (let i = 0; i < that.data.buttons.length; i++) {
            if (that.data.buttons[i]) {
              that.setData({
                ['buttons[' + i + '].btclass']: that.btnclass(that.data.buttons[i].value)
              });
              console.log(that.data.buttons);
            }
          }
          wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: that.data.themeBaseColor,
            animation: {
              duration: 400,
              timingFunc: 'easeIn'
            }
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  debounceMoneyInp: debounce(function (e) {
    if (this.options.plugin === 'store_oil_station') {
      this.moneyChange();
    }
  }, 300),
  async moneyChange() {
    if (!this.data.money) return;
    let obj = this.data.plugins_new[this.options.plugin];
    if (!obj.preApi) return;
    let json = {};
    for (const key in obj.preParams) {
      json[key] = this.data[obj.preParams[key]] ? this.data[obj.preParams[key]] : null;
    }
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss(obj.preApi),
      data: json
    })
    if (data.result) {
      this.setData({
        member_coupon_list: data.data.member_coupon_list,
        recharge_new: data.data.recharge
      })
    } else {
      app.tips(data.msg);
    }
  },
  toSignV2(){
    wx.navigateTo({
      url: '/packageH/sign_shopV2/index/index?scene=7',
    });
  },
  toSignDetail(){
    wx.navigateTo({
      url: `/packageH/signPage/signPage?id=${this.data.sign_info.contract_id}`,
    });
  },
  moneyinp(e) {
    let val = e.detail.value;
    this.setData({
      money: val
    });
    if(this.options.plugin == 'store_oil_station'){
      let filtetarr = null;
      filtetarr = this.data.diy_amount.findIndex((item)=>{
        return this.data.money == item.amount
      })
      this.setData({
        diy_money_index: filtetarr < 0 ? this.data.diy_amount.length : filtetarr
      })
      console.log(filtetarr)
    }
    this.debounceMoneyInp(e);
  },
  priceDifferencePool_confirm(type){
    console.log(this.data.money)
    let json ={
      pay_id:type,
      amount:this.data.money
    }
    let urlStr = app.getNetAddresss("plugin.price-difference-pool.frontend.modules.pool.controllers.recharge.apply");
    app._postNetWork({
      url: urlStr,
      data:json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.rechargePay({
            pay_type: type,
            data: res,
            ordersn: res.data.order_sn,
            type: 'price-difference-pool'
          });
        } else {
          app.tips(res.msg);
        }
      }
    });
  },
  // YCC start
  getMergaPay(ids,btn,type){
    let url = app.getNetAddresss("order.merge-pay");
    app._getNetWork({
      url: url,
      data:{
        order_ids:ids
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.data.order_pay_id = res.data.order_pay.id;
          this.data.pid = res.data.order_pay.uid;
          if(btn.other.need_password){
            // ycc资产 充值余额
            this.setData({
              popupSpecs:true
            })
            return
          }
          this.handlePay(btn,type)
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  payKeyboardClose(e){
    this.setData({
      popupSpecs:false
    })
  },
  payKeyboardComplete(e){
    this.getVerifyPassword(e.detail,'','');
  },
  yccConfirm(type,btn){
    let url = app.getNetAddresss("plugin.ycc-money.frontend.create.index");
    app._getNetWork({
      url: url,
      data:{
        ycc_money_price:this.data.money
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let ids = res.data.order_ids;
          this.getMergaPay(ids,btn,type)
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  // 确认充值
  confirm_post(e) {
    let type = e.currentTarget.dataset.val;
    if(this.data.need_sign){
      wx.showModal({
        title: '温馨提示',
        confirmText: '去签署',
        content: `根据平台要求，您需完成《${this.data.sign_info.contract_name}》合同签署后再充值${this.data.balanceLang}！`,
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/packageH/sign_shopV2/index/index?scene=7',
            });
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    if(this.data.diymoney) this.data.money = this.data.diymoney;

    if(app._isTextEmpty(this.data.money)){
      app.tips('请输入有效金额')
      return
    }
    this.setData({
      money: parseFloat(this.data.money),
      pay_type: type
    });
    if(this.data.priceDifferencePool){
      this.priceDifferencePool_confirm(type);
      return
    }
    if (this.data.money <= 0) {
      wx.showToast({
        icon: 'none',
        title: '金额不可低于0',
        duration: 1500
      });
      return;
    }
    if(this.data.plugName == 'YccRecharge'){
      let { btn } = e.currentTarget.dataset;
      this.yccConfirm(type,btn)
      return
    }
    let urlStr = app.getNetAddresss('finance.balance.recharge');
    if(this.data.tagBalance){
      urlStr = app.getNetAddresss('plugin.tag-balance.frontend.recharge.index');
    }
    urlStr += '&client_type=2';
    urlStr += '&app_type=wechat';
    let _json = {
      pay_type:this.data.pay_type,
      recharge_money:this.data.money,
    }
    let obj = this.data.plugins_new[this.options.plugin];
    if(this.options.plugin == 'store_oil_station'){
      for (const key in obj.preParams) {
        _json[key] = this.data[obj.preParams[key]] ? this.data[obj.preParams[key]] : null;
      }
    }

    //判断this.plugin_code是否有值，有_json添加plugin_code属性，并把this.plugin_code对象里的值赋给它，用逗号隔开
    if(this.data.plugin_code){
      for (const key in this.data.plugin_code) {
        if(key&&this.data.plugin_code[key]) {
          _json.plugin_code = this.data.plugin_code[key];
        }
      }
    }
    app._postNetWork({
      url: urlStr,
      data:_json,
      success: (resdata)=> {
        var res = resdata.data;
        // console.log(res.data)
        if (res.result == 1) {
          if(this.data.pay_type == '88'){
            wx.showModal({
                title:'',
                showCancel:false,
                content:'充值成功',
                success:function(res){
                wx.navigateBack({
                    delta:1
                })
                }
            })
            return
          }
          if (app._isTextEmpty(res.data.ordersn) && this.data.pay_type != '140' && this.data.pay_type != 132) {
            wx.showToast({
              icon: 'none',
              title: '参数错误',
              duration: 1500
            });
            return;
          }
          this.setData({
            ordersn: res.data.ordersn
          });
          this.rechargePay({
            pay_type: type,
            data: res,
            ordersn: res.data.ordersn,
            type: 'balance'
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          if(type == 102){
            if(res.data.eplus_bind_mobile == 1){
              // 绑定手机
              wx.navigateTo({
                url: '/packageF/others/wisdom/wisdomBind/wisdomBind?option=phone&to=pay',
              })
              app.tips(resdata.msg)
            }
          }
        }
      },
      fail:(res)=> {
        console.log(res);
      }
    });
  },
  selectActivityNum(e){
    let num = e.currentTarget.dataset.num;
    this.setData({
      money: num,
      diy_money_index: this.data.diy_amount.length,
      diymoney: num
    })
  },
  selectDiyNum(e){
    let num = e.currentTarget.dataset.index;
    if(this.options.plugin == 'store_oil_station'){
      this.setData({
        money: this.data.diy_amount[num]?this.data.diy_amount[num].amount:'',
        diy_money_index: num,
        diymoney: ''
      });
      return
    }
    this.setData({
      money: this.data.diy_amount[num],
      diy_money_index: num,
      diymoney: ''
    });
  },
  selectPlugBtn(e ){
    let { name, code } = e.currentTarget.dataset;
    this.data.plugin_code[name] = code;
    this.setData({
      plugin_code: this.data.plugin_code
    });
  },
});
